package cn.com.jcoo;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import java.util.Locale;

/**
 * 配置http请求Locale解析器
 */
@RequiredArgsConstructor
@Configuration
public class HttpRequestLocaleResolver implements LocaleResolver {
    private final HttpServletRequest httpServletRequest;

    public Locale getLocale() {
        return resolveLocale(httpServletRequest);
    }

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
//		String lang = request.getHeader("lang");
        String lang = request.getParameter("lang");
        if (!StringUtils.hasLength(lang)) {
            return Locale.getDefault();
        }
        // return new Locale(lang);
        if (lang.contains("-")) {
            String[] split = lang.split("_");
            return new Locale(split[0], split[1]);
        }
        return new Locale(lang);

    }

    /**
     * 用于实现Locale的切换。比如SessionLocaleResolver获取Locale的方式是从session中读取，但如果
     * 用户想要切换其展示的样式(由英文切换为中文)，那么这里的setLocale()方法就提供了这样一种可能
     *
     * @param request
     * @param response
     * @param locale
     */
    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response,
                          Locale locale) {

    }
}
